#!/usr/bin/python
# coding=utf-8

# 20180804
# author：葛木瓜
# 从西安房管局意向登记平台爬取已完成的登记信息
# 长安区登记平台
# http://124.115.228.93/zfrgdjpt/xmgsca.aspx
# 非长安区登记平台
# http://124.115.228.93/zfrgdjpt/xmgs.aspx

from selenium import webdriver
from byCsv import *
from time import sleep


class GetPrice:
    """
    获取当前登记的项目情况
    包括：项目名、申请总数、刚需家庭、刚需家庭、
    """
    def __init__(self, url):

        self.url = url
        self.price_csv = './csvData/xm_price.csv'
        # self.driver = webdriver.Firefox()
        # self.driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])
        self.driver = webdriver.PhantomJS(executable_path='D:\\Python36\\phantomjs.exe')
        self.driver.get(url)
        self.driver.implicitly_wait(5)

    def get_price(self):
        """
        获取项目当前登记的情况
        :return:
        """
        price_csv = self.price_csv
        driver = self.driver
        regis_lst = driver.find_elements_by_xpath('.//*[@class="xmgsItem"]/div[1]/div[1]/span[1]')
        for regis_lst_i in range(len(regis_lst)):
            cur_xm_lst = []
            driver.switch_to.default_content()
            xm_name = regis_lst[regis_lst_i].text
            if check_from_csv(price_csv, xm_name) is None:

                # 判断如果csv里面没有项目则追加该项目及价格，否则跳过

                cur_xm_lst.append(regis_lst[regis_lst_i].text)
                driver.execute_script("arguments[0].scrollIntoView();", regis_lst[regis_lst_i])
                sale_announce_lst = driver.find_elements_by_xpath('//*/span[text()="销售公告"]')
                sale_announce_lst[regis_lst_i].click()

                driver.switch_to.frame('layui-layer-iframe%d' % (regis_lst_i + 1))
                sleep(0.5)
                span = driver.find_elements_by_xpath("//*/span")
                # 优化获取价格，增加重复获取价格的逻辑，使得获取价格更稳定
                for span_i in range(len(span)):
                    if '均价' in span[span_i].text:
                        # print(span[span_i].text)
                        xm_price = span[span_i].text.split('均价')[1].split('元/')[0]
                        if xm_price == '约' or xm_price == '':
                            while True:
                                try:
                                    xm_price = span[span_i + 1].text
                                    if float(xm_price) < 5000 or float(xm_price) > 30000:
                                        span_i += 1
                                    else:
                                        break
                                except ValueError as e:
                                    print('ValueError:', e)
                                    span_i += 1
                        cur_xm_lst.append(xm_price.strip() + '元/㎡')
                        add_csv(price_csv, cur_xm_lst)
                        break
                driver.find_element_by_xpath('//*/span[text()="关闭"]').click()
        driver.quit()
